package top.lixunda.ecommerce.server.user.config;

import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;


/**
 * @author LiXunda
 * @version time:2019/10/25 11:40
 * <p>
 * seata需要代理dataSource
 */
@SuppressWarnings("Duplicates")
@Configuration
@Slf4j
@RefreshScope
public class DataSourceProxyAutoConfiguration {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    public DataSourceProxyAutoConfiguration() {
        log.debug("my DataSourceProxyAutoConfiguration");
    }

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Primary
    @Bean
    public DataSourceProxy dataSourceProxy() {
        HikariDataSource dataSource = new HikariDataSource();
        log.debug("添加seata代理数据源");
        dataSource.setJdbcUrl(url);
        log.debug("proxy datasource : url : {}", dataSource.getJdbcUrl());
        dataSource.setUsername(username);
        log.debug("proxy datasource : username : {}", dataSource.getUsername());
        dataSource.setPassword(password);
        log.debug("proxy datasource : driverClassName : {}", dataSource.getDriverClassName());
        dataSource.setDriverClassName(driverClassName);
        return new DataSourceProxy(dataSource);
    }

}
